{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "da22a6e7",
   "metadata": {},
   "source": [
    "# Coherence Evaluator\n",
    "\n",
    "### Getting Started\n",
    "This sample demonstrates how to use the Coherence evaluator to assess the quality and readability of AI-generated responses. The evaluator measures the ability of the language model to generate text that reads naturally, flows smoothly, and resembles human-like language.\n",
    "\n",
    "Before you begin:\n",
    "```bash\n",
    "pip install azure-ai-evaluation\n",
    "```\n",
    "Set these environment variables with your own values:\n",
    "1) **MODEL_DEPLOYMENT_NAME** - The deployment name of the model for this AI-assisted evaluator, as found under the \"Name\" column in the \"Models + endpoints\" tab in your Azure AI Foundry project.\n",
    "2) **AZURE_OPENAI_ENDPOINT** - Azure Open AI Endpoint to be used for evaluation.\n",
    "3) **AZURE_OPENAI_API_KEY** - Azure Open AI Key to be used for evaluation.\n",
    "4) **AZURE_OPENAI_API_VERSION** - Azure Open AI Api version to be used for evaluation."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48f8cb64",
   "metadata": {},
   "source": [
    "The Coherence evaluator assesses the ability of the language model to generate text that reads naturally, flows smoothly, and resembles human-like language in its responses. It measures the readability and user-friendliness of the model's generated responses.\n",
    "\n",
    "Coherence scores range from 1 to 5:\n",
    "\n",
    "<pre>\n",
    "Score 1: Very Poor - The response is completely incoherent with no logical flow or connection between ideas.\n",
    "Score 2: Poor - The response has significant coherence issues with disjointed ideas and unclear transitions.\n",
    "Score 3: Fair - The response is somewhat coherent but has noticeable gaps in logical flow or organization.\n",
    "Score 4: Good - The response is mostly coherent with good flow and logical connections between ideas.\n",
    "Score 5: Excellent - The response is perfectly coherent with smooth, natural flow and clear logical progression.\n",
    "</pre>\n",
    "\n",
    "The evaluation requires one of the following input patterns:\n",
    "\n",
    "**Pattern 1: Query-Response Evaluation**\n",
    "- Query: The user's question or prompt. (string)\n",
    "- Response: The AI-generated response to be evaluated for coherence. (string)\n",
    "\n",
    "**Pattern 2: Conversation Evaluation**\n",
    "- Conversation: A multi-turn conversation where each turn is evaluated for coherence. (dict with \"messages\" key)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "542c1340",
   "metadata": {},
   "source": [
    "### Initialize Coherence Evaluator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35799119",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from azure.ai.evaluation import CoherenceEvaluator, AzureOpenAIModelConfiguration\n",
    "from pprint import pprint\n",
    "\n",
    "model_config = AzureOpenAIModelConfiguration(\n",
    "    azure_endpoint=os.environ[\"AZURE_OPENAI_ENDPOINT\"],\n",
    "    api_key=os.environ[\"AZURE_OPENAI_API_KEY\"],\n",
    "    api_version=os.environ[\"AZURE_OPENAI_API_VERSION\"],\n",
    "    azure_deployment=os.environ[\"MODEL_DEPLOYMENT_NAME\"],\n",
    ")\n",
    "\n",
    "coherence_evaluator = CoherenceEvaluator(model_config=model_config)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b10aff00",
   "metadata": {},
   "source": [
    "### Samples"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "724adfc8",
   "metadata": {},
   "source": [
    "#### Query and Response as Strings (str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "82a1be93",
   "metadata": {},
   "outputs": [],
   "source": [
    "query = \"Can you explain how machine learning works?\"\n",
    "response = \"Machine learning is a subset of artificial intelligence that enables systems to learn and improve from experience without being explicitly programmed. It works by analyzing data patterns to make predictions or decisions. First, the system is trained on a dataset, which allows it to identify patterns and relationships. Then, it uses these learned patterns to make predictions on new, unseen data. The accuracy improves over time as the model processes more data and refines its understanding.\"\n",
    "\n",
    "result = coherence_evaluator(query=query, response=response)\n",
    "pprint(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bc250127",
   "metadata": {},
   "source": [
    "#### Example of Poor Coherence"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "62ad5478",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Poor coherence example\n",
    "query = \"What is blockchain technology?\"\n",
    "response = \"Blockchain is decentralized. Bitcoin uses it. Blocks contain data. Cryptography is involved. Banks might use blockchain. It's secure because of the chain. Mining is how new blocks are added. Digital currencies exist. The ledger is distributed.\"\n",
    "\n",
    "result = coherence_evaluator(query=query, response=response)\n",
    "pprint(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1d22e3d6",
   "metadata": {},
   "source": [
    "#### Conversation as Dict with Messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "556c197b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Multi-turn conversation\n",
    "conversation = {\n",
    "    \"messages\": [\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"I'm planning a trip to Japan. What should I know?\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"assistant\",\n",
    "            \"content\": \"Japan is a fascinating destination with a rich cultural heritage. First, you should know that the best times to visit are spring (March-May) for cherry blossoms and fall (September-November) for autumn colors. The country has an excellent public transportation system, particularly the Shinkansen bullet train network. Additionally, learning a few basic Japanese phrases will be appreciated by locals, though many signs in major cities have English translations.\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"What about the food?\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"assistant\",\n",
    "            \"content\": \"Japanese cuisine is incredibly diverse and delicious. Beyond the well-known sushi and ramen, you should try regional specialties like okonomiyaki in Osaka or motsunabe in Fukuoka. Most restaurants display plastic food models in their windows, which makes ordering easier even with a language barrier. It's also important to note that tipping is not customary in Japan and can sometimes be considered rude.\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"user\",\n",
    "            \"content\": \"Are there any cultural customs I should be aware of?\"\n",
    "        },\n",
    "        {\n",
    "            \"role\": \"assistant\",\n",
    "            \"content\": \"Yes, there are several important customs to observe. Always remove your shoes when entering homes, temples, and some traditional restaurants. Bowing is a common greeting, though a slight nod is acceptable for foreigners. When using chopsticks, never stick them upright in rice as this resembles a funeral ritual. Finally, be mindful of noise levels on public transportation, as talking on phones or having loud conversations is considered impolite.\"\n",
    "        }\n",
    "    ]\n",
    "}\n",
    "\n",
    "result = coherence_evaluator(conversation=conversation)\n",
    "pprint(result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "test_agent_evaluator_prp",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
